
(function (mui, own) {
	/**
	 * 获取应用本地配置
	 **/
	own.setSettings = function (settings) {
		settings = settings || {};
		console.log(JSON.stringify(settings));
		localStorage.setItem('vasoe_setting', JSON.stringify(settings));
	}

	/**
	 * 设置应用本地配置
	 **/
	own.getSettings = function () {
		var settingsText = localStorage.getItem('vasoe_setting') || "{}";
		if(settingsText == "{}"){
			/*2018-08-06 侯连文 读取默认配置*/
			plus.io.requestFileSystem( plus.io.PRIVATE_WWW, function( fs ) {
				// 通过fs.root获取DirectoryEntry对象进行操作 
				fs.root.getFile('default.json',{create:true}, function(fileEntry){
					fileEntry.file( function(file){
						var fileReader = new plus.io.FileReader();
						fileReader.readAsText(file, 'utf-8');
						fileReader.onloadend = function(evt) {
							settingsText = evt.target.result || "{}";
							
							vasoe.setSettings(JSON.parse(settingsText));
						}
					} );
				});
			}, function ( e ) {
				plus.nativeUI.alert( "Request file system failed: " + e.message );
			} );
		}
		return JSON.parse(settingsText);
	}
	
	/**
	 * 用户登录
	 **/
	own.login = function (loginInfo, callback) {
		callback = callback || mui.noop;
		var appSetting = own.getSettings();
		if(appSetting.ServerUrl == undefined || appSetting.ServerUrl == "")
			return callback(-1,"服务器地址不能为空！");
		loginInfo = loginInfo || {};
		loginInfo.Account = loginInfo.Account || '';
		loginInfo.Password = loginInfo.Password || '';
		if (loginInfo.Account.length < 1) {
			return callback(-1,'登录账号不能为空！');
		}
		if (loginInfo.Password.length < 6) {
			return callback(-1,'密码最短为 6 个字符');
		}
		/*
		var users = JSON.parse(localStorage.getItem('vasoe_userInfo') || '[]');
		var authed = users.some(function (user) {
			return loginInfo.account == user.account && loginInfo.password == user.password;
		});
		if (authed) {
			return vasoe.createState(loginInfo.account, callback);
		} else {
			return callback('用户名或密码错误');
		}
		*/
		console.log(appSetting.ServerUrl + '/api/CorpRegister/CheckLogin');
		mui.ajax(appSetting.ServerUrl + '/api/CorpRegister/CheckLogin', {
			data: {
				Account: loginInfo.Account,
				Password: md5(loginInfo.Password)
			},
			dataType: 'json', //数据格式类型
			type: 'GET', //http请求类型
			timeout: 60000, //超时设置
			success: function(result) {
				console.log(JSON.stringify(result));
				//处理成功返回的数据
				if(result.ResultType == 0) {
					vasoe.createLogin(appSetting.ServerUrl, loginInfo.Account, result.DataObject, callback);
					callback(1,'登录成功!');
				} else {
					callback(-1,result.Message);
				}
			},
			error: function(result) {
				console.log(JSON.stringify(result));
				callback(-1,'登录异常:');
			}
		});
	};
	/**
	* 获取登录信息
	**/
	own.getLoginInfo = function () {
		var logininfo = localStorage.getItem('vasoe_logininfo') || "{}";
		return JSON.parse(logininfo);
	};

	/**
	 * 设置登录信息
	 **/
	own.setLoginInfo = function (logininfo) {
		logininfo = logininfo || {};
		console.log("vasoe_logininfo="+JSON.stringify(logininfo));
		localStorage.setItem('vasoe_logininfo', JSON.stringify(logininfo));
	};
	
	own.createLogin = function (serverUrl,account,operator, callback) {
		var logininfo = {};
		logininfo.serverUrl = serverUrl;
		logininfo.account = account;
		logininfo.operator = operator;
		own.setLoginInfo(logininfo);
		return callback(1,"");
	};
	/**
	 * 新用户注册
	 **/
	own.register = function (registerInfo, callback) {
		callback = callback || mui.noop;
		var appSetting = own.getSettings();
		if(appSetting.ServerUrl == undefined || appSetting.ServerUrl == "")
			return callback(-1,"服务器地址不能为空！");
		registerInfo = registerInfo || {};
		registerInfo.AuthId = registerInfo.AuthId || '';
		registerInfo.OpenId = registerInfo.OpenId || '';
		registerInfo.CorpCode = registerInfo.CorpCode || '';
		registerInfo.CorpName = registerInfo.CorpName || '';
		registerInfo.CorpLinkman = registerInfo.CorpLinkman || '';
		registerInfo.CorpTele = registerInfo.CorpTele || '';
		registerInfo.Password = registerInfo.Password || '';
		if (registerInfo.CorpCode.length < 1) {
			return callback(-1,'店铺名称不能为空！');
		}
		if (registerInfo.CorpName.length < 1) {
			return callback(-1,'店铺名称不能为空！');
		}
		if (registerInfo.CorpLinkman.length < 1) {
			return callback(-1,'联系人不能为空！');
		}
		if (registerInfo.CorpTele.length < 6) {
			return callback(-1,'手机号码不能为空！');
		}
		/*
		if (!checkEmail(registerInfo.email)) {
			return callback(-1,'邮箱地址不合法');
		}
		*/
		/*
		var users = JSON.parse(localStorage.getItem('vasoe_userInfo') || '[]');
		users.push(regInfo);
		localStorage.setItem('vasoe_userInfo', JSON.stringify(users));
		return callback();
		*/
		//console.log(registerInfo.ServerUrl + '/api/CorpRegister/TenantSubmit');
		mui.ajax(appSetting.ServerUrl + '/api/CorpRegister/TenantSubmit', {
			data: {
				AuthId:registerInfo.AuthId,
				OpenId:registerInfo.OpenId,
				CorpCode: registerInfo.CorpCode,
				CorpName: registerInfo.CorpName,
				CorpLinkman: registerInfo.CorpLinkman,
				CorpTele: registerInfo.CorpTele,
				Password: registerInfo.Password,
			},
			dataType: 'json', //数据格式类型
			type: 'POST', //http请求类型
			timeout: 60000, //超时设置
			success: function(data) {
				console.log(JSON.stringify(data));
				//处理成功返回的数据
				if(data.ResultType == 0) {
					callback(1,"保存成功!");
				} else {
					callback(-1,data.Message);
				}
			},
			error: function(data) {
				console.log(JSON.stringify(data));
				callback(-1,'注册异常！');
			}
		});
	};
	var checkEmail = function (email) {
		email = email || '';
		return (email.length > 3 && email.indexOf('@') > -1);
	};

	/**
	 * 找回密码
	 **/
	own.forgetPassword = function (email, callback) {
		callback = callback || $.noop;
		if (!checkEmail(email)) {
			return callback('邮箱地址不合法');
		}
		return callback(null, '新的随机密码已经发送到您的邮箱，请查收邮件。');
	};

	
	/**
	 * 获取本地是否安装客户端
	 **/
	own.isInstalled = function (id) {
		if (id === 'qihoo' && mui.os.plus) {
			return true;
		}
		if (mui.os.android) {
			var main = plus.android.runtimeMainActivity();
			var packageManager = main.getPackageManager();
			var PackageManager = plus.android.importClass(packageManager)
			var packageName = {
				"qq": "com.tencent.mobileqq",
				"weixin": "com.tencent.mm",
				"sinaweibo": "com.sina.weibo"
			}
			try {
				return packageManager.getPackageInfo(packageName[id], PackageManager.GET_ACTIVITIES);
			} catch (e) {}
		} else {
			switch (id) {
				case "qq":
					var TencentOAuth = plus.ios.import("TencentOAuth");
					return TencentOAuth.iphoneQQInstalled();
				case "weixin":
					var WXApi = plus.ios.import("WXApi");
					return WXApi.isWXAppInstalled()
				case "sinaweibo":
					var SinaAPI = plus.ios.import("WeiboSDK");
					return SinaAPI.isWeiboAppInstalled()
				default:
					break;
			}
		}
	}
	
	own.page = null;
	own.openPage = function(url, id, styles, extras, onClosePage){
		plus.nativeUI.showWaiting();
		// 打开新窗口
		page=plus.webview.create(url, id, styles, extras);
		page.addEventListener('loaded', function(){
			console.log('New Window loaded!');
			plus.nativeUI.closeWaiting();
		}, false);
		page.onclose = onClosePage;
		page.show("pop-in"); // 显示窗口
	};
	
	own.appendPage = function(url,id,param){
		plus.nativeUI.showWaiting();
		// 打开新窗口
		page=plus.webview.create(url,id,param);
		page.addEventListener('loaded', function(){
			console.log('New Window append!');
			plus.nativeUI.closeWaiting();
		}, false);
		plus.webview.currentWebview().append(page); // 显示窗口
	};
	
	own.get = function(id) {
		return document.getElementById(id);
	};
	
	own.getData = function(url,data,message,callback){
		
		var appSetting = own.getSettings();
		if(appSetting.ServerUrl == undefined || appSetting.ServerUrl == "")
			return callback(-1,"服务器地址不能为空！");
		console.log(appSetting.ServerUrl + url)	;
		
		message = message || "读取数据...";
		plus.nativeUI.showWaiting(message);	
		mui.ajax(appSetting.ServerUrl + url, {
			data: data,
			dataType: 'json', //数据格式类型
			type: 'GET', //http请求类型
			timeout: 60000, //超时设置
			success: function(result) {
				console.log(JSON.stringify(result));
				plus.nativeUI.closeWaiting();
				//处理成功返回的数据
				if(result.ResultType == 0) {
					callback(1,"获取数据成功!",result);
				} else {
					callback(-1,result.Message);
				}
			},
			error: function(result) {
				console.log(JSON.stringify(result));
				plus.nativeUI.closeWaiting();
				callback(-1,'获取数据异常！');
			}
		});
	};
	own.postData = function(url,data,callback){
		var appSetting = own.getSettings();
		if(appSetting.ServerUrl == undefined || appSetting.ServerUrl == "")
			return callback(-1,"服务器地址不能为空！");
			
		plus.nativeUI.showWaiting("提交数据...");		
		mui.ajax(appSetting.ServerUrl + url, {
			data: data,
			dataType: 'json', //数据格式类型
			type: 'POST', //http请求类型
			timeout: 60000, //超时设置
			success: function(result) {
				console.log(JSON.stringify(result));
				plus.nativeUI.closeWaiting();
				//处理成功返回的数据
				if(result.ResultType == 0) {
					callback(1,"提交数据成功!");
				} else {
					callback(-1,result.Message);
				}
			},
			error: function(result) {
				console.log(JSON.stringify(result));
				plus.nativeUI.closeWaiting();
				callback(-1,'提交数据异常！');
			}
		});
	};
	/**
	* 获取状态信息-用于界面传参
	**/
	own.getState = function () {
		var state = localStorage.getItem('vasoe_state') || "{}";
		return JSON.parse(state);
	};

	/**
	 * 设置状态信息-用于界面传参
	 **/
	own.setState = function (state) {
		state = state || {};
		console.log("vasoe_state="+JSON.stringify(state));
		localStorage.setItem('vasoe_state', JSON.stringify(state));
	};
	
	/**
	* 获取用户分类
	**/
	own.getClassify = function () {
		var state = localStorage.getItem('shiquan_classify') || "{}";
		return JSON.parse(state);
	};
	/**
	 * 设置用户分类-用于界面传参
	 **/
	own.setClassify = function (key,value) {
		var classify = own.getClassify();
		classify[key] = value;
		console.log("shiquan_classify="+JSON.stringify(classify));
		localStorage.setItem('shiquan_classify', JSON.stringify(classify));
	};
	/**
	* 删除用户分类
	**/
	own.delClassify = function () {
		localStorage.setItem('shiquan_classify', "{}");
	};
	/**
	* 获取用户分类
	**/
	own.getBooks = function () {
		var state = localStorage.getItem('shiquan_books') || "{}";
		return JSON.parse(state);
	};
	/**
	 * 设置用户分类-用于界面传参
	 **/
	own.setBook = function (key,book) {
		var books = own.getBooks();
		books[key] = book;
		console.log("shiquan_books="+JSON.stringify(books));
		localStorage.setItem('shiquan_books', JSON.stringify(books));
	};
	/**
	 * 设置用户分类-用于界面传参
	 **/
	own.delBooks = function () {
		localStorage.setItem('shiquan_books', "{}");
	};
	/*打开界面*/
	own.openView = function(options) {
		options = options || {};
		if(options.url == undefined) {
			plus.nativeUI.alert("页面文件-Url 不能为空！");
			return;
		}
		if(options.id == undefined) {
			plus.nativeUI.alert("页面标识-id 不能为空！");
			return;
		}
		options.createNew = options.createNew || false; //是否重复创建同样id的webview，默认为false:不重复创建，直接显示
		options.styles = options.styles || {};
		options.extras = options.extras || {};
		options.show = options.show || {
			autoShow: true, //页面loaded事件发生后自动显示，默认为true
			aniShow: 'pop-in'
		};
		options.waiting = options.waiting || {
			autoShow: true, //自动显示等待框，默认为true
			title: '正在加载...', //等待对话框上显示的提示内容
		};
		mui.openWindow({
			url: options.url,
			id: options.id,
			createNew: options.createNew,
			styles: options.styles,
			extras: options.extras,
			show: options.show,
			waiting: options.waiting
		});
	};
	/*
	 * 压缩文件
	 */
	own.compressImage = function(src, dst, callback) {
		callback = callback || $.noop;
		plus.zip.compressImage({
				src: src,
				dst: dstname,
				overwrite: true,
				quality: 50
			},
			function(event) {
				callback({
					state: 1,
					file: event.target
				});
			},
			function(error) {
				callback({
					state: -1,
					error: error
				});
			});
	}
	/*
	 * 拍照获取图片
	 */
	own.getCamera = function(callback) {
		callback = callback || $.noop;
		var camera = plus.camera.getCamera();
		camera.captureImage(function(e) {
			plus.io.resolveLocalFileSystemURL(e, function(entry) {
				callback({
					state: 1,
					message: "拍照成功",
					entry: entry
				});
			}, function(e) {
				plus.nativeUI.alert("读取拍照文件错误：" + e.message);
				callback({
					state: -1,
					mesage: e.message
				});
			});
		}, function(s) {
			plus.nativeUI.alert("拍照异常：" + s);
			callback({
				state: -1,
				mesage: s
			});
		}, {
			filename: "_doc/camera/"
		});
	}
	/*
	 * 选取图片
	 */
	own.galleryImg = function(callback) {
		callback = callback || $.noop;
		plus.gallery.pick(function(file) {
			callback({
				state: 1,
				message: "选取图片",
				file: file
			});
		}, function(e) {
			callback({
				state: -1,
				message: "取消选择"
			});
		}, {
			filter: "image"
		});
	}
	/*
	 * 选取图片
	 */
	own.galleryImgs = function(callback) {
		callback = callback || $.noop;
		plus.gallery.pick(function(e) {
			callback({
				state: 1,
				files: e.files
			});
		}, function(e) {
			callback({
				state: -1,
				mesage: "取消选择"
			});
		}, {
			filter: "image",
			multiple: true
		});
	}
	/*
	 * 选择日期
	 */
	own.datePicker = function(el,options,callback){
		callback = callback || $.noop;
		var _self = el;
		if(_self.picker) {
			_self.picker.show(function (rs) {
				//result.innerText = '选择结果: ' + rs.text;
				callback(rs);
				_self.picker.dispose();
				_self.picker = null;
			});
		} else {
			/*
			var optionsJson = el.getAttribute('data-options') || '{}';
			var options = JSON.parse(optionsJson);
			var id = el.getAttribute('id');
			*/
			options = options || {type:"date",beginYear:2010,endYear:2099};
			/*
			 * 首次显示时实例化组件
			 * 示例为了简洁，将 options 放在了按钮的 dom 上
			 * 也可以直接通过代码声明 optinos 用于实例化 DtPicker
			 */
			_self.picker = new mui.DtPicker(options);
			_self.picker.show(function(rs) {
				/*
				 * rs.value 拼合后的 value
				 * rs.text 拼合后的 text
				 * rs.y 年，可以通过 rs.y.vaue 和 rs.y.text 获取值和文本
				 * rs.m 月，用法同年
				 * rs.d 日，用法同年
				 * rs.h 时，用法同年
				 * rs.i 分（minutes 的第二个字母），用法同年
				 */
				//result.innerText = '选择结果: ' + rs.text;
				callback(rs);
				/*
				 * 返回 false 可以阻止选择框的关闭
				 * return false;
				 */
				/*
				 * 释放组件资源，释放后将将不能再操作组件
				 * 通常情况下，不需要示放组件，new DtPicker(options) 后，可以一直使用。
				 * 当前示例，因为内容较多，如不进行资原释放，在某些设备上会较慢。
				 * 所以每次用完便立即调用 dispose 进行释放，下次用时再创建新实例。
				 */
				_self.picker.dispose();
				_self.picker = null;
			});
		}
	}
	//---------------------------------------------------
	// 日期格式化
	// 格式 YYYY/yyyy/YY/yy 表示年份
	// MM/M 月份
	// W/w 星期
	// dd/DD/d/D 日期
	// hh/HH/h/H 时间
	// mm/m 分钟
	// ss/SS/s/S 秒
	//---------------------------------------------------
	own.dateFormat = function(dateVal, fmt) {
		var dataObj;
		if(dateVal instanceof Date) {
			dataObj = dateVal;
		} else {
			dataObj = new Date(dateVal);
		}
		var o = {
			"M+": dataObj.getMonth() + 1, //月份
			"d+": dataObj.getDate(), //日
			"h+": dataObj.getHours() % 12 == 0 ? 12 : dataObj.getHours() % 12, //小时
			"H+": dataObj.getHours(), //小时
			"m+": dataObj.getMinutes(), //分
			"s+": dataObj.getSeconds(), //秒
			"q+": Math.floor((dataObj.getMonth() + 3) / 3), //季度
			"S": dataObj.getMilliseconds() //毫秒
		};
		var week = {
			"0": "/u65e5",
			"1": "/u4e00",
			"2": "/u4e8c",
			"3": "/u4e09",
			"4": "/u56db",
			"5": "/u4e94",
			"6": "/u516d"
		};

		fmt = fmt || "yyyy-MM-dd";
		if(/(y+)/.test(fmt) && fmt!=undefined) {
			fmt = fmt.replace(RegExp.$1, (dataObj.getFullYear() + "").substr(4 - RegExp.$1.length));
		}

		if(/(E+)/.test(fmt) && fmt!=undefined) {
			fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[dataObj.getDay() + ""]);
		}
		for(var k in o) {
			if(new RegExp("(" + k + ")").test(fmt)) {
				fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
			}
		}
		return fmt;
	};
	
	/**
	 * 格式化时间的辅助类，将一个时间转换成x小时前、y天前等
	 */
	own.dateUtils = {
		UNITS: {
			'年': 31557600000,
			'月': 2629800000,
			'天': 86400000,
			'小时': 3600000,
			'分钟': 60000,
			'秒': 1000
		},
		humanize: function(milliseconds) {
			var humanize = '';
			mui.each(this.UNITS, function(unit, value) {
				if(milliseconds >= value) {
					humanize = Math.floor(milliseconds / value) + unit + '前';
					return false;
				}
				return true;
			});
			return humanize || '刚刚';
		},
		format: function(dateStr) {
			var date = this.parse(dateStr)
			var diff = Date.now() - date.getTime();
			if(diff < this.UNITS['天']) {
				return this.humanize(diff);
			}
			
			var _format = function(number) {
				return(number < 10 ? ('0' + number) : number);
			};
			return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' + _format(date.getHours()) + ':' + _format(date.getMinutes());
		},
		parse:function (str) {//将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
			var a = str.split(/[^0-9]/);
			return new Date (a[0],a[1]-1,a[2],a[3],a[4],a[5] );
		}
	};
}(mui, window.app = {}));